package com.cn.qgx428.lazydiary.ui.timeline

import android.content.Context
import android.support.v4.app.FragmentActivity
import android.util.Log
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import com.cn.qgx428.lazydiary.R
import com.cn.qgx428.lazydiary.db.bean.CStikyNote
import com.cn.qgx428.lazydiary.db.dao.StikyNoteDao
import com.cn.qgx428.lazydiary.extension.getCurrenDayOfYear
import com.cn.qgx428.lazydiary.extension.getCurrenTimePrecise
import com.cn.qgx428.lazydiary.ui.activity.StickNoteActivity
import com.cn.qgx428.lazydiary.ui.activity.subActivity.StickNoteChangeActivity
import org.jetbrains.anko.startActivity
import java.text.SimpleDateFormat
import java.util.*

/**
 * Created by qinguanxiong on 2018/4/4.
 */
class T_Stikynote(context: Context, mView: View?) : T_Base(context, mView) {
    lateinit var txt: TextView
    lateinit var mainLayout: LinearLayout
    lateinit var currentST: CStikyNote

    companion object {
        val NOTICETIME = "noticeTime"
    }

    override fun initView() {
        txt = getView(R.id.timeline_stikyNote_txt)
        mainLayout = getView(R.id.timeline_stikynote_layout)
    }

    override fun initEvent() {

    }

    override fun getData() {
        val format = SimpleDateFormat("yyyy年MM月dd日", Locale.CHINA)
        val currenTime = format.format(Calendar.getInstance().time)
       // 最近待办事项
        val dao = StikyNoteDao()
        val builder = dao.getBuilder()
        var cs: List<CStikyNote>? = dao.getBuilder().orderBy(NOTICETIME, true)
                .limit(1)
                .where()
                .ge(NOTICETIME,currenTime)
                .query()
        if (cs != null && cs.size > 0){
            updateUI(cs.get(0))
        }  else{
            // 为空的话，取最近一次添加的
            cs = StikyNoteDao().getBuilder().orderBy("id", false)
                    .limit(1)
                    .query()
            if (cs!=null && cs.size > 0){
                updateUI(cs.get(0))
            } else{
                //隐藏当前布局
                mainLayout.visibility = View.GONE
            }
        }
    }


    fun updateUI(stikyNote: CStikyNote){
        Log.d("nnnkk","create")
        currentST = stikyNote
        mainLayout.visibility = View.VISIBLE
        txt.text = currentST.content
        mainLayout.setOnClickListener { mContext.startActivity<StickNoteActivity>() }
    }

    override fun onDataChange() {
        getData()
    }
}